using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Reflection;
using System.Xml.Linq;
using 日志的使用.自定义的内容;

namespace 日志的使用.Controllers
{
    //[Authorize]
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IMemoryCache memoryCache; //使用服务器缓存，需要在Program中添加 builder.Services.AddMemoryCache();
        private readonly IDistributedCache redisCache;  //Redis缓存      

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IMemoryCache cache, IDistributedCache distributedCache)
        {
            _logger = logger;
            this.memoryCache = cache;
            redisCache = distributedCache;
        }

        //[HttpGet(Name = "GetWeatherForecast")]  
        [HttpGet()]
        [AllowAnonymous]  //与[Authorize]配合使用，表示允许任何访问
        [TypeFilter(typeof(SelfActionPartFilter))]
        public async Task<IEnumerable<WeatherForecast>> Get(CancellationToken token)
        {
            var exists = await redisCache.KeyExistsByRedisAsync("ThisWeather");
            
            var values = await redisCache.GetOrCreateAsync<IEnumerable<WeatherForecast>>("ThisWeather", option =>
            {
                option.SetSlidingExpiration(TimeSpan.FromSeconds(50));
                option.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
                return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = Random.Shared.Next(-20, 55),
                    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
                }).ToArray();
            });


            //DistributedCacheEntryOptions options = new DistributedCacheEntryOptions();
            //options.SetSlidingExpiration(TimeSpan.FromSeconds(50));
            //options.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));
            //await redisCache.SetAsync("ThisWeather", values, options);


            //var values = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            //{
            //    Date = DateTime.Now.AddDays(index),
            //    TemperatureC = Random.Shared.Next(-20, 55),
            //    Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            //}).ToArray();

            //读取计算机环境变量的值，该值会有延迟的问题，
            var environmentVal = Environment.GetEnvironmentVariable("DefaultDB_ConnStr", EnvironmentVariableTarget.Machine);

            _logger.LogInformation($"{values.FirstOrDefault().Date}记录一下这个是Info级别的日志", values);

            return values;
        }

        [ResponseCache(Duration = 60)] //告诉浏览器缓存60秒
        [HttpGet("{name}/{age}")]
        public ActionResult<string> Getstr(string name, int age)
        {
            //本地缓存使用
            var value = memoryCache.GetOrCreateAsync<string>("CacheKey", item =>
             {
                 item.SlidingExpiration = TimeSpan.FromSeconds(5); //滑动过期时间5秒
                 item.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(15);  // 设置缓存有效时间为15秒
                 return Task.FromResult<string>("这是返回的内容");
             });

            DistributedCacheEntryOptions options = new DistributedCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(5)).SetSlidingExpiration(TimeSpan.FromSeconds(20));


            redisCache.SetString("thisKey", "thisValue" + DateTime.Now, options);

            //[FromRoute(Name ="name")]
            return $"接收的信息Name{name},年龄为{age}，缓存中的内容" + value.Result;
        }

        /// <summary>
        /// 中间件过滤器
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [MiddlewareFilter(typeof(SelfMiddleWareFilter))]
        [HttpGet()]
        public ActionResult<String> MiddleWarefilterSimple(string name) 
        {
            return "这是中间件过滤器" + name;
        }

        [HttpGet()]
        public FileResult DownloadImage(String fileName)
        {
            string fileUrl = $"{Directory.GetCurrentDirectory()}\\Files\\{fileName}";
            if (!System.IO.File.Exists(fileUrl))
            { 
                fileUrl= $"{Directory.GetCurrentDirectory()}\\Files\\NoImage.jpg";
            }
            using (FileStream stream = new FileStream(fileUrl, FileMode.Open))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Seek(0, SeekOrigin.Begin);
                return File(buffer, "image/jpg", fileName);
            }
        }
    }
}